/*
 *	Perlin Production Co. Ltd. September 2012 (c).
 *			paramlib.c
 */
 
#include "paramlib.h"

 /* InitParm(ip++, 'd', 1, DEFSD	, MAXSD	, "sprite depth"); */


 
InitParm(_ip, _key, _min, _val, _max, _name) /*ctor*/
INTPARM* _ip;
char	_key;
int	_min;
int	_val;
int	_max;
char	*_name;
{
	_ip->ip_key	= _key;
	_ip->ip_rep	= 0; 	/* 0 to avoid multiple value redefinitions */
	_ip->ip_min	= _min;
	_ip->ip_val	= _val;	/* defaul value originally */
	_ip->ip_max	= _max;
	_ip->ip_name	= _name;
}
	


INTPARM* FindParm(_param, _key, _numparm)
INTPARM		*_param;
char		_key;
unsigned	_numparm;
{
	int	i;
	INTPARM	*result;
	
	result = 0;
	
	for (i=result; !result && i < _numparm; ++i)
	{
		if (_param->ip_key == tolower(_key)) result = _param;
		else ++_param;
	}
	return result;
}
			



int	ArgInt(_value, _min, _max, _name)
char*	_value;
int	_min;
int	_max;
char*	_name;	/* parameter name */
{
	int	result;
	char	text[0xFF];
	char	*c;

	if (_max < _min)
	{
		result	= _min;
		_min	= _max;
		_max	= result;
	}
	
	if (!*_value) trouble(_name,"parameter has no value");
	
	for (c = _value; *c; ++c)
		if (!isdigit(*c)) trouble("invalid parameter value", c);
			
	
	result = atoi(_value);

	if (result < _min || result > _max)
	{
		sprintf	( text
			, "parameter %s = %d is out of [%d,%d] range"
			, _name
			, result
			, _min
			, _max
			);
		trouble (text,0);
	}
	return result;
}



OptParm(_argv, _argb, _argc, _param, _numparm)
char		**_argv;
int		_argb;
int		_argc;
INTPARM		*_param;
unsigned	_numparm;
{
	int	i;
	char	*option;
	INTPARM	*found;
	
	for (i=_argb; i < _argc; ++i)
	{
		option	= _argv[i];
		if ((*option != '-')
		/*	|| (*(option+2) != '=') */
		) trouble("invalid input at", option);
			
		found = FindParm(_param, *++option, _numparm);
		if (found)
		{
		 if (found->ip_rep++)
			trouble("multiple parameter redefinition", found->ip_name);
			
		 found->ip_val = ArgInt(++option, found->ip_min
		 			, found->ip_max, found->ip_name);
		}
		else trouble ("invalid parameter",option);
	}
	
	for (i=0; i < _numparm; ++i)
	{
	    found = &_param[i];
	    if (found->ip_rep && _param[IP_VERBOSE].ip_val)
		 printf("%s is set to %d\n",found->ip_name, found->ip_val);
	}
}
